package main

import (
	"errors"
	"os"

	"gitee.com/RickieL/ip4region"

	"gitee.com/RickieL/comm"
	"github.com/gin-gonic/gin"
)

func main() {

	// ip, err := Region.BinarySearch("1.20.133.1")
	// fmt.Printf("BinarySearch: ip:%#v \n, err: %v\n", ip, err)

	// ip, err = Region.BtreeSearch("1.20.133.1")
	// fmt.Printf("BtreeSearch: ip:%#v \n, err: %v\n", ip, err)

	r := gin.Default()
	r.GET("/:ip", getIPInfo)
	r.Run(":9527") // listen and serve on 0.0.0.0:9527
}

func getIPInfo(c *gin.Context) {
	appG := Gin{C: c}
	ip := c.Param("ip")
	t := c.DefaultQuery("t", "json")
	to := ""

	if t == "pretty" || t == "str" {
		to = t
	} else {
		to = "json"
	}

	if !comm.IsIP(ip) {
		err := errors.New(ip + " 不是ip地址，请填写正确的ip地址！")
		appG.Response(400, "err", to, err.Error())
		return
	}

	db := "./ip4region.db"
	_, err := os.Stat(db)
	if os.IsNotExist(err) {
		err := errors.New(db + " 不存在，请检查！")
		appG.Response(400, "err", to, err.Error())
		return
	}

	Region, err := ip4region.New(db)
	defer Region.Close()

	res, err := Region.BtreeSearch(ip)
	if err != nil {
		appG.Response(400, "err", to, err.Error())
		return
	}

	appG.Response(0, "ok", to, res)
}

//Gin gin结构体
type Gin struct {
	C *gin.Context
}

// Response 返回
func (g *Gin) Response(errCode int, msg string, to string, data interface{}) {

	if to == "json" {
		g.C.JSON(200, gin.H{
			"code": errCode,
			"msg":  msg,
			"data": data,
		})
	} else if to == "pretty" {
		g.C.IndentedJSON(200, data)
	} else if to == "str" {
		g.C.String(200, "%v", data)
	}

	return
}
